import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

# 获取用户列表
def doGetuserList():
   try:
      logger.info('131:获取用户列表');
      conn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      conn.request("GET", "/openapi/user/list?query=&pageNo=1&pageSize=100", payload, headers)
      res = conn.getresponse()
      data = res.read()
      # print(data.decode("utf-8"))
      logger.info('131:' + data.decode("utf-8"))
      conn.close()
   except Exception as e:
      logger.info('131:错误'+str(e));

# 新增或编辑用户2
def doSendUser(py_flag,py_no,py_dict):
    try:
        conn = http.client.HTTPSConnection(global_url)
        payload=json.dumps(py_dict)
        headers = {
            'app-id': global_appid,
            'app-key': global_appkey,
            'Content-Type': 'application/json'
        }
        conn.request("POST", "/openapi/user/added", payload, headers)
        res = conn.getresponse()
        data = res.read()
        data = data.decode("utf-8")
        # print(data.decode("utf-8"))
        logger.info('132:' + data)
        conn.close()

        if (py_flag == 2):
            print("修改")
        else:
            # 新增 依据返回值刷新id
            json_str = json.loads(data)
            ierrCode = json_str["errCode"]
            if (ierrCode == 200):
                data_json = json_str["data"]
                id = data_json["id"]
                # print(id, end="\n")
                sql = "update am_sys_user  set update_time=NOW()"
                sql = sql + ",create_id=" + str(id)
                sql = sql + " where id=" + str(py_no)
                sql = sql + " and fsite_no_belong='" + global_site + "';"
                # print(sql)
                conn, cursor = postsql_utility.get_conn()
                i = postsql_utility.execute(sql=sql, cursor=cursor, connect=conn)
                if i != "OK":
                    print("失败" + str(i))
                else:
                    print("成功" + str(i))

    except Exception as e:
        logger.info('132:错误'+str(e));

# 新增或编辑用户
def doAdduser():
   try:
      logger.info('132:新增或编辑用户');
      # payload = json.dumps({
      #     "id": 401,
      #     "roleId": 4,
      #     "doors": [],
      #     "status": True,
      #     "departmentIds": [
      #         4,
      #         3
      #     ],
      #     "name": "张飞",
      #     "phone": "13001010101",
      #     "cardNo": "这是卡号",
      #     "email": "zhuce@wyl.im",
      #     "jobNo": "jobno",
      #     "password": "Kaka@0000",
      #     "confirmPassword": "Kaka@0000"
      # })
      sql = "select a.id,c.create_id roleId,a.username,a.phone,a.fcard"
      sql = sql +" ,a.email,a.note,a.password_clear,a.status"
      sql = sql +" from am_sys_user a,am_sys_user_role b,am_sys_role c"
      sql = sql +" where 1=1"
      sql = sql +" and a.fsite_no_belong='"+global_site+"'"
      sql = sql +" and ((a.create_id is null) or (a.create_id=0))"
      sql = sql +" and a.id=b.user_id"
      sql = sql +" and b.role_id=c.id"
      sql = sql +" order by a.status,a.id;"
      logger.info('102:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data = postsql_utility.select(sql=sql, cursor=cursor)

      for j1 in range(len(data)):
          data_dict = {}
          data_dict["id"] = data[j1][0]
          #用户角色必选
          role_list = [data[j1][1]]
          data_dict["roleIdList"] = role_list
          #data_dict["roleId"] = 4
          doors_list = []
          data_dict["doors"] = doors_list
          data_dict["status"] = True
          #错误的部门信息
          dep_list=[112]
          data_dict["departmentIds"] = dep_list
          data_dict["name"] = data[j1][2]
          data_dict["phone"] = data[j1][3]
          data_dict["cardNo"] = data[j1][4]
          data_dict["email"] = data[j1][5]
          data_dict["jobNo"] = data[j1][6]
          #密码不合格，密码不能小于6位，且必须包含数字、大小写字母
          data_dict["password"] = data[j1][7]
          data_dict["confirmPassword"] = data[j1][7]
          #data_dict["password"] = "Kaka@0000"
          #data_dict["confirmPassword"] = "Kaka@0000"
          print(data_dict)
          doSendUser(1,data[j1][0],data_dict)

   except Exception as e:
      logger.info('132:错误'+str(e));

#直接调试
#doAdduser()
